import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/mine/login_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/regex_util.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/mine/my_web_page.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class MyLoginPage extends StatefulWidget {
  const MyLoginPage({super.key});

  @override
  State<MyLoginPage> createState() => _MyLoginPageState();
}

class _MyLoginPageState extends State<MyLoginPage> {
  final logic =
      Get.put(LoginLogic(), tag: Get.arguments == LoginType.bind ? '1' : '0');
  final phoneC = TextEditingController();
  final codeC = TextEditingController();
  final focusNode = FocusNode();
  bool firstClick = true;

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      focusNode.addListener(() {
        bool hasFocus = focusNode.hasFocus;
        if (hasFocus) {
        } else {}
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          backgroundColor: Colours.transparent,
          leading: IconButton(
            onPressed: Get.back,
            icon: Image.asset(
              Utils.getImgPath('close.png'),
              width: 24,
              height: 24,
              color: Colours.black,
            ),
          ),
        ),
        resizeToAvoidBottomInset: false,
        body: SafeArea(
            top: false,
            child: Stack(
              children: [
                Image.asset(Utils.getImgPath("login_bg.png"),
                    width: Get.width,
                    height: Get.width * 812 / 375,
                    fit: BoxFit.cover),
                Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      padding:
                          const EdgeInsets.only(top: 120, left: 20, bottom: 30),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.asset(Utils.getImgPath("login_welcome_bg.png"),
                              width: 200, height: 38, fit: BoxFit.cover),
                          const QsText('体育赛事数据平台 为您的胜利导航', color: Colours.N8),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Container(
                          decoration: const BoxDecoration(
                              color: Colours.N1,
                              borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(24))),
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 30, left: 20, right: 20),
                            child: Column(children: [
                              phoneWidget(),
                              const SizedBox(height: 20),
                              vefiyCodeWidget(),
                              const SizedBox(height: 18),
                              privacyWidget(),
                              const SizedBox(height: 50),
                              loginButton(onTap: () {
                                login();
                              }),
                            ]),
                          )),
                    ),
                  ],
                )
              ],
            )));
  }

  Widget loginButton({String? buttonText, Function()? onTap, double? width}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        //width: width ?? 84,
        height: 48,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: (phoneC.text.length == 11 &&
                      codeC.text.length == 6 &&
                      firstClick == false)
                  ? [Color(0xFF4774F0), Color(0xFF82A5F0)]
                  : [Colours.B3, Colours.B3],
            ),
            borderRadius: BorderRadius.circular(24)),
        child: QsText(buttonText ?? '登录',
            needCenter: true,
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colours.N1),
      ),
    );
  }

  phoneWidget() {
    return Container(
      decoration: BoxDecoration(
          color: Colours.greyF2F3F7, borderRadius: BorderRadius.circular(24)),
      child: Row(children: [
        Image.asset(
          Utils.getImgPath('login_icon_phone.png'),
          width: 16,
          height: 17,
        ).paddingOnly(left: 25),
        Container(
            width: 60,
            alignment: Alignment.center,
            child: const QsText('+86', fontSize: 16, color: Colours.N9)),
        Container(
          width: 1,
          height: 20,
          color: Colours.greyCC,
        ),
        Expanded(
            child: TextField(
          controller: phoneC,
          keyboardType: TextInputType.number,
          style: const TextStyle(color: Colours.N9, fontSize: 16),
          inputFormatters: [
            FilteringTextInputFormatter.allow((RegExp(RegexUtil.number)))
          ],
          onChanged: (value) {
            update();
          },
          decoration: InputDecoration(
            border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(4),
                borderSide: BorderSide.none),
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
            hintText: "请输入手机号",
            hintStyle: const TextStyle(fontSize: 16, color: Colours.N6),
            suffixIconConstraints:
                const BoxConstraints(minHeight: 16, minWidth: 20),
            suffixIcon: phoneC.text.isEmpty
                ? null
                : GestureDetector(
                    onTap: () {
                      setState(() {
                        phoneC.text = '';
                      });
                    },
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Image.asset(
                        Utils.getImgPath('grey_close.png'),
                        width: 16,
                        height: 16,
                      ),
                    ),
                  ),
          ),
        ))
      ]),
    );
  }

  vefiyCodeWidget() {
    return Container(
      decoration: BoxDecoration(
          color: Colours.greyF2F3F7, borderRadius: BorderRadius.circular(24)),
      child: Row(children: [
        Image.asset(
          Utils.getImgPath('login_icon_lock.png'),
          width: 16,
          height: 17,
        ).paddingOnly(left: 25),
        Expanded(
            child: TextField(
          controller: codeC,
          keyboardType: TextInputType.number,
          style: const TextStyle(color: Colours.N9, fontSize: 16),
          inputFormatters: [
            FilteringTextInputFormatter.allow((RegExp(RegexUtil.number)))
          ],
          onChanged: (value) {
            update();
          },
          decoration: InputDecoration(
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(4),
                  borderSide: BorderSide.none),
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
              hintText: "请输入验证码",
              hintStyle: const TextStyle(fontSize: 16, color: Colours.N6),
              suffixIconConstraints:
                  const BoxConstraints(minHeight: 16, minWidth: 20),
              suffixIcon: vefiyButtonWidget()),
        ))
      ]),
    );
  }

  vefiyButtonWidget() {
    return Obx(() => QsButton(
            text: logic.currentTime == 60
                ? '获取验证码'
                : (logic.currentTime == 0
                    ? '重发验证码'
                    : '（${logic.currentTime}秒）'),
            width: 88,
            height: 28,
            textStyle: const TextStyle(fontSize: 13),
            backgroundColor: (phoneC.text.length == 11 &&
                    (firstClick || 0 == logic.currentTime))
                ? Colours.B6
                : Colours.B3,
            foregroundColor: Colours.N1,
            onPressed: next)
        .marginOnly(right: 8));
  }

  privacyWidget() {
    return Row(children: [
      const SizedBox(width: 10),
      RichText(
          strutStyle: Styles.centerStyle(fontSize: 12),
          text: TextSpan(children: [
            WidgetSpan(
                child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: logic.agreeUserPrivacy,
                    child: Obx(() => Padding(
                        padding: const EdgeInsets.only(right: 4, bottom: 1),
                        child: logic.agreePrivacy.value
                            ? Image.asset(
                                Utils.getImgPath('login_icon_check_select.png'),
                                width: 13,
                                height: 13,
                              )
                            : Image.asset(
                                Utils.getImgPath('login_icon_check_normal.png'),
                                width: 13,
                                height: 13,
                              ))))),
            TextSpan(children: [
              const TextSpan(
                  text: '已同意',
                  style: TextStyle(color: Colours.N8, fontSize: 12)),
              TextSpan(
                  text: '《服务协议》',
                  style: const TextStyle(color: Colours.B6, fontSize: 12),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () => Get.toNamed(Routes.webview,
                        arguments: WebPara(Constant.serviceAgreementUrl,
                            longpress: true))),
              const TextSpan(
                  text: '和',
                  style: TextStyle(color: Colours.grey99, fontSize: 12)),
              TextSpan(
                  text: '《隐私政策》',
                  style:
                      const TextStyle(color: Colours.blue2766D6, fontSize: 12),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.toNamed(Routes.webview,
                          arguments: WebPara(Constant.privacyPolicyUrl,
                              longpress: true));
                    })
            ])
          ]))
    ]);
  }

  thirdLoginWidget() {
    return Center(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            onTap: () => logic.onWechatLogin(),
            child: Image.asset(
              Utils.getImgPath('login_wx.png'),
              width: 40,
            ),
          ),
          const SizedBox(width: 38),
          GestureDetector(
            onTap: () => logic.onQQLogin(),
            child: Image.asset(
              Utils.getImgPath('login_qq.png'),
              width: 40,
            ),
          ),
        ],
      ),
    );
  }

  next() async {
    FocusScope.of(context).requestFocus(focusNode);
    if (phoneC.text.length == 11) {
      if (firstClick) {
        var result = await logic.doSendSms(phoneC.text);
        if (result == true) firstClick = false;
      } else if (logic.currentTime == 0) {
        logic.resendSms();
      }
    }
  }

  login() async {
    if (firstClick == false) logic.doLogin(codeC.text);
  }
}
